/**
 * Copyright  2025, Hai Yue Xing He  ZHAO LIMIN
 *
 * @author        ZHAO LIMIN
 * @version       1.0.1
 * @since         2025-04
 * Matrix2.ts     矩形类
 * 一个矩阵类，用于计算二维矩阵的各种操作。
 * 这个类实现了ArrayLike<number>接口，这意味着它可以像数组一样被索引。
 * 这个类还提供了一些静态方法，用于创建矩阵。
 * 这个类还提供了一些实例方法，用于计算矩阵的各种操作。
 * 这个类还提供了一些静态方法，用于计算矩阵的各种操作。
 */
import { ICartesian } from './Cartesian'
import { Cartesian2 } from './Cartesian2'
import { Check } from './Check'
import { defined } from './Defined'
import { DeveloperError } from './DeveloperError'
import { UNION_NUMBER_ARRAY } from './HDataType'
import { INumberArray } from './HXArray'
import { defaultValue } from './HYXHDefaultValue'
import { IMatrix } from './Matrix'

/**
 * A 2x2 matrix, indexable as a column-major order array.
 * Constructor parameters are in row-major order for code readability.
 * @alias Matrix2
 * @constructor
 * @implements {ArrayLike<number>}
 *
 * @param {number} [column0Row0=0.0] The value for column 0, row 0.
 * @param {number} [column1Row0=0.0] The value for column 1, row 0.
 * @param {number} [column0Row1=0.0] The value for column 0, row 1.
 * @param {number} [column1Row1=0.0] The value for column 1, row 1.
 *
 * @see Matrix2.fromArray
 * @see Matrix2.fromColumnMajorArray
 * @see Matrix2.fromRowMajorArray
 * @see Matrix2.fromScale
 * @see Matrix2.fromUniformScale
 * @see Matrix2.fromRotation
 * @see Matrix3
 * @see Matrix4
 */

export class Matrix2 implements IMatrix, INumberArray {
  [index: number]: number
  constructor(
    column0Row0?: number,
    column1Row0?: number,
    column0Row1?: number,
    column1Row1?: number,
  ) {
    this[0] = column0Row0 ?? 0.0
    this[1] = column0Row1 ?? 0.0
    this[2] = column1Row0 ?? 0.0
    this[3] = column1Row1 ?? 0.0
  }
  /**
   * 填充
   * @param items 
   * @returns 
   */
  push(...items: number[]): number[] {
    this[0] = items[0]
    this[1] = items[1]
    this[2] = items[2]
    this[3] = items[3]
    return [this[0], this[1], this[2], this[3]]
  }
  /**
   * 用于将对象打包到数组中的元素数。
   * @type {number}
   */
  public static readonly packedRowLength = 2
  public static readonly packedColLength = 2
  public static readonly packedLength = Matrix2.packedRowLength * Matrix2.packedColLength
  /**
   * Stores the provided instance into the provided array.
   *
   * @param {Matrix2} value The value to pack.
   * @param {number[]} array The array to pack into.
   * @param {number} [startingIndex=0] The index into the array at which to start packing the elements.
   *
   * @returns {number[]} The array that was packed into
   */
  public static pack(
    value: Matrix2,
    array: Array<number>,
    startingIndex: number = 0,
  ): Array<number> {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('value', value)
    Check.defined('array', array)
    //>>includeEnd('debug');

    startingIndex = startingIndex ?? 0

    array[startingIndex++] = value[0]
    array[startingIndex++] = value[1]
    array[startingIndex++] = value[2]
    array[startingIndex++] = value[3]

    return array
  }
  /**
   * Retrieves an instance from a packed array.
   *
   * @param {number[]} array The packed array.
   * @param {number} [startingIndex=0] The starting index of the element to be unpacked.
   * @param {Matrix2} [result] The object into which to store the result.
   * @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided.
   */
  public static unpack(array: Array<number>, startingIndex: number, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.defined('array', array)
    //>>includeEnd('debug');

    startingIndex = startingIndex ?? 0
    if (!defined(result)) {
      result = new Matrix2()
    }

    result[0] = array[startingIndex++]
    result[1] = array[startingIndex++]
    result[2] = array[startingIndex++]
    result[3] = array[startingIndex++]
    return result
  }
  /**
   * 将Matrix2数组展平为组件数组。组件
   * 以列优先顺序存储。
   *
   * @param {Matrix2[]} array The array of matrices to pack.
   * @param {number[]} [result] 用于存储结果的数组。如果这是一个类型数组，则必须有array.length * 4个组件，否则将抛出a
   *                            {@link DeveloperError}。如果它是一个普通数组，则会调整大小以包含
   *                           （array.length * 4）个元素。
   * @returns {number[]} The packed array.
   */
  public static packArray(array: Array<Matrix2>, result: Array<number>): Array<number> {
    //>>includeStart('debug', pragmas.debug);
    Check.defined('array', array)
    //>>includeEnd('debug');
    const length = array.length
    const resultLength = length * Matrix2.packedLength
    if (!defined(result)) {
      result = new Array(resultLength)
    } else if (!Array.isArray(result)) {
      //>>includeStart('debug', pragmas.debug);Unpacks an array of column-major matrix components into an array of Matrix2s.
      throw new DeveloperError(
        'If result is a typed array, it must have exactly array.length * 4 elements',
      )
      //>>includeEnd('debug');
    } else if (result.length !== resultLength) {
      result.length = resultLength
    }
    for (let i = 0; i < length; ++i) {
      Matrix2.pack(array[i], result, i * Matrix2.packedLength)
    }
    return result
  }

  /**
   * 将一列按柱顺序排列的矩阵组件解包到一列Matrix2数组中
   *
   * @param {number[]} array The array of components to unpack.
   * @param {Matrix2[]} [result] The array onto which to store the result.
   * @returns {Matrix2[]} The unpacked array.
   */
  public static unpackArray(array: Array<number>, result: Array<Matrix2>): Array<Matrix2> {
    //>>includeStart('debug', pragmas.debug);
    Check.defined('array', array)
    Check.typeOf.tnumber.greaterThanOrEquals('array.length', array.length, Matrix2.packedLength)
    if (array.length % Matrix2.packedLength !== 0) {
      throw new DeveloperError('array length must be a multiple of 4.')
    }
    //>>includeEnd('debug');

    const length = array.length
    if (!defined(result)) {
      result = new Array(length / Matrix2.packedLength)
    } else {
      result.length = length / Matrix2.packedLength
    }

    for (let i = 0; i < length; i += Matrix2.packedLength) {
      const index = i / Matrix2.packedLength
      result[index] = Matrix2.unpack(array, i, result[index])
    }
    return result
  }
  /**
   * 克隆一个Matrix2对象实例
   *
   * @param {Matrix2} matrix The matrix to duplicate.
   * @param {Matrix2} [result] The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided. (Returns
   * undefined if matrix is undefined)
   */
  public static clone(matrix: Matrix2, result: Matrix2): Matrix2 | undefined {
    if (!defined(matrix)) {
      return undefined
    }
    if (!defined(result)) {
      return new Matrix2(matrix[0], matrix[2], matrix[1], matrix[3])
    }
    result[0] = matrix[0]
    result[1] = matrix[1]
    result[2] = matrix[2]
    result[3] = matrix[3]
    return result
  }

  /**
   * Creates a Matrix2 from 4 consecutive elements in an array.
   *
   * @function
   * @param {number[]} array The array whose 4 consecutive elements correspond to the positions of the matrix.
   * Assumes column-major order.
   * @param {number} [startingIndex=0] The offset into the array of the first element, which corresponds to first
   * column first row position in the matrix.
   * @param {Matrix2} [result] The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided.
   *
   * @example
   * // Create the Matrix2:
   * // [1.0, 2.0]
   * // [1.0, 2.0]
   *
   * const v = [1.0, 1.0, 2.0, 2.0];
   * const m = Matrix2.fromArray(v);
   *
   * // Create same Matrix2 with using an offset into an array
   * const v2 = [0.0, 0.0, 1.0, 1.0, 2.0, 2.0];
   * const m2 = Matrix2.fromArray(v2, 2);
   */
  public static fromArray = Matrix2.unpack
  /**
   * Creates a Matrix2 instance from a column-major order array.
   *
   * @param {number[]} values 按列主序排列的数组
   * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be *
   * created.
   * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
   */
  public static fromColumnMajorArray(values: Array<number>, result: Matrix2): Matrix2 | undefined {
    //>>includeStart('debug', pragmas.debug);
    Check.defined('values', values)
    //>>includeEnd('debug');
    return Matrix2.unpack(values, 0, result)
  }
  /**
   * 从行优先顺序数组创建Matrix2实例。
   * 生成的矩阵将以列优先顺序排列。
   *
   * @param {number[]} values The row-major order array.
   * @param {Matrix2} [result] 结果将存储在的对象，如果未定义，则将创建一个新的实例创建。
   * @returns {Matrix2}         修改后的结果参数，如果没有提供，则为新的Matrix2实例。
   */
  public static fromRowMajorArray(values: Array<number>, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.defined('values', values)
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Matrix2(values[0], values[1], values[2], values[3])
    }
    result[0] = values[0]
    result[1] = values[2]
    result[2] = values[1]
    result[3] = values[3]
    return result
  }
  /**
   * 计算一个表示非均匀缩放的Matrix2实例。
   *
   * @param {Cartesian2} scale The x and y scale factors.
   * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
   *
   * @example
   * // Creates
   * //   [7.0, 0.0]
   * //   [0.0, 8.0]
   * const m = Matrix2.fromScale(new Cartesian2(7.0, 8.0));
   */
  public static fromScale(scale: ICartesian, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('scale', scale)
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Matrix2(scale.x, 0.0, 0.0, scale.y)
    }

    result[0] = scale.x
    result[1] = 0.0
    result[2] = 0.0
    result[3] = scale.y
    return result
  }

  /**
   * 计算一个表示均匀缩放的Matrix2实例。
   *
   * @param {number} scale The uniform scale factor.
   * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
   *
   * @example
   * // Creates
   * //   [2.0, 0.0]
   * //   [0.0, 2.0]
   * const m = public static fromUniformScale(2.0);
   */
  public static fromUniformScale(scale: number, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('scale', scale)
    //>>includeEnd('debug');

    if (!defined(result)) {
      return new Matrix2(scale, 0.0, 0.0, scale)
    }

    result[0] = scale
    result[1] = 0.0
    result[2] = 0.0
    result[3] = scale
    return result
  }

  /**
   * Creates a rotation matrix.
   *
   * @param {number} angle The angle, in radians, of the rotation.  Positive angles are counterclockwise.
   * @param {Matrix2} [result] The object in which the result will be stored, if undefined a new instance will be created.
   * @returns {Matrix2} The modified result parameter, or a new Matrix2 instance if one was not provided.
   *
   * @example
   * // Rotate a point 45 degrees counterclockwise.
   * const p = new Cartesian2(5, 6);
   * const m = Matrix2.fromRotation(Math.toRadians(45.0));
   * const rotated = Matrix2.multiplyByVector(m, p, new Cartesian2());
   */
  public static fromRotation(angle: number, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.number('angle', angle)
    //>>includeEnd('debug');

    const cosAngle = Math.cos(angle)
    const sinAngle = Math.sin(angle)

    if (!defined(result)) {
      return new Matrix2(cosAngle, -sinAngle, sinAngle, cosAngle)
    }
    result[0] = cosAngle
    result[1] = sinAngle
    result[2] = -sinAngle
    result[3] = cosAngle
    return result
  }

  /**
   * Creates an Array from the provided Matrix2 instance.
   * The array will be in column-major order.
   *
   * @param {Matrix2} matrix The matrix to use..
   * @param {number[]} [result] The Array onto which to store the result.
   * @returns {number[]} The modified Array parameter or a new Array instance if one was not provided.
   */
  public static toArray(matrix: Matrix2, result?: UNION_NUMBER_ARRAY): UNION_NUMBER_ARRAY | undefined {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    //>>includeEnd('debug');

    if (!defined(result)) {
      return [matrix[0], matrix[1], matrix[2], matrix[3]]
    }
    result![0] = matrix[0]
    result![1] = matrix[1]
    result![2] = matrix[2]
    result![3] = matrix[3]
    return result
  }
  /**
   * 计算指定行和列处元素的数组索引。
   *
   * @param {number} row The zero-based index of the row.
   * @param {number} column The zero-based index of the column.
   * @returns {number} The index of the element at the provided row and column.
   *
   * @exception {DeveloperError} row must be 0 or 1.
   * @exception {DeveloperError} column must be 0 or 1.
   *
   * @example
   * const myMatrix = new Matrix2();
   * const column1Row0Index = Matrix2.getElementIndex(1, 0);
   * const column1Row0 = myMatrix[column1Row0Index]
   * myMatrix[column1Row0Index] = 10.0;
   */
  public static getElementIndex(column: number, row: number): number {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.tnumber.greaterThanOrEquals('row', row, 0)
    Check.typeOf.tnumber.lessThanOrEquals('row', row, 1)

    Check.typeOf.tnumber.greaterThanOrEquals('column', column, 0)
    Check.typeOf.tnumber.lessThanOrEquals('column', column, 1)
    //>>includeEnd('debug');
    return column * 2 + row
  }
  /**
   * Retrieves a copy of the matrix column at the provided index as a Cartesian2 instance.
   *
   * @param {Matrix2} matrix The matrix to use.
   * @param {number} index The zero-based index of the column to retrieve.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0 or 1.
   */
  public static getColumn(
    matrix: Matrix2, 
    index: number, 
    result?: ICartesian): ICartesian | undefined {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    Check.typeOf.tnumber.greaterThanOrEquals('index', index, 0)
    Check.typeOf.tnumber.lessThanOrEquals('index', index, 1)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');
    const startIndex = index * 2
    const x = matrix[startIndex]
    const y = matrix[startIndex + 1]
    if (!defined(result)) {
      return new Cartesian2(x, y)
    }
    result!.x = x
    result!.y = y
    return result
  }
  /**
   * 计算一个新的矩阵，用提供的Cartesian2实例替换所提供的矩阵中的指定列。
   *
   * @param {Matrix2} matrix The matrix to use.
   * @param {number} index The zero-based index of the column to set.
   * @param {Cartesian2} cartesian The Cartesian whose values will be assigned to the specified column.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0 or 1.
   */
  public static setColumn(
    matrix: Matrix2,
    index: number,
    cartesian: ICartesian,
    result: Matrix2,
  ): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)

    Check.typeOf.tnumber.greaterThanOrEquals('index', index, 0)
    Check.typeOf.tnumber.lessThanOrEquals('index', index, 1)

    Check.typeOf.object('cartesian', cartesian)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    result = defaultValue<Matrix2>(Matrix2.clone(matrix, result), new Matrix2())
    const startIndex = index * 2
    result[startIndex] = cartesian.x
    result[startIndex + 1] = cartesian.y
    return result
  }
  /**
   * Retrieves a copy of the matrix row at the provided index as a Cartesian2 instance.
   *
   * @param {Matrix2} matrix The matrix to use.
   * @param {number} index The zero-based index of the row to retrieve.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0 or 1.
   */
  public static getRow(
    matrix: Matrix2,
    index: number,
    result?: ICartesian): ICartesian | undefined {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)

    Check.typeOf.tnumber.greaterThanOrEquals('index', index, 0)
    Check.typeOf.tnumber.lessThanOrEquals('index', index, 1)

    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    const x = matrix[index]
    const y = matrix[index + 2]
    if (!defined(result)) {
      return new Cartesian2(x, y)
    }
    result!.x = x
    result!.y = y
    return result
  }
  /**
   * 计算一个新的矩阵，用提供的Cartesian2实例替换所提供的矩阵中的指定行。
   *
   * @param {Matrix2} matrix The matrix to use.
   * @param {number} index The zero-based index of the row to set.
   * @param {Cartesian2} cartesian The Cartesian whose values will be assigned to the specified row.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   * @exception {DeveloperError} index must be 0 or 1.
   */
  public static setRow(
    matrix: Matrix2,
    index: number,
    cartesian: ICartesian,
    result: Matrix2,
  ): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)

    Check.typeOf.tnumber.greaterThanOrEquals('index', index, 0)
    Check.typeOf.tnumber.lessThanOrEquals('index', index, 1)

    Check.typeOf.object('cartesian', cartesian)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');
    Matrix2.clone(matrix, result)
    result[index] = cartesian.x
    result[index + 2] = cartesian.y
    return result
  }
  /**
   * Computes a new matrix that replaces the scale with the provided scale.
   * This assumes the matrix is an affine transformation.
   *
   * @param {Matrix2} matrix The matrix to use.
   * @param {Cartesian2} scale The scale that replaces the scale of the provided matrix.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   * @see Matrix2.setUniformScale
   * @see Matrix2.fromScale
   * @see Matrix2.fromUniformScale
   * @see Matrix2.multiplyByScale
   * @see Matrix2.multiplyByUniformScale
   * @see Matrix2.getScale
   */
  public static setScale(matrix: Matrix2, scale: ICartesian, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    Check.typeOf.object('scale', scale)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    const existingScale = Matrix2.getScale(matrix, scaleScratch1) as Cartesian2
    const scaleRatioX = scale.x / existingScale.x
    const scaleRatioY = scale.y / existingScale.y

    result[0] = matrix[0] * scaleRatioX
    result[1] = matrix[1] * scaleRatioX
    result[2] = matrix[2] * scaleRatioY
    result[3] = matrix[3] * scaleRatioY

    return result
  }
  /**
   * Computes a new matrix that replaces the scale with the provided uniform scale.
   * This assumes the matrix is an affine transformation.
   *
   * @param {Matrix2} matrix The matrix to use.
   * @param {number} scale The uniform scale that replaces the scale of the provided matrix.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   * @see Matrix2.setScale
   * @see Matrix2.fromScale
   * @see Matrix2.fromUniformScale
   * @see Matrix2.multiplyByScale
   * @see Matrix2.multiplyByUniformScale
   * @see Matrix2.getScale
   */
  public static setUniformScale(matrix: Matrix2, scale: number, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    Check.typeOf.number('scale', scale)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    const existingScale = Matrix2.getScale(matrix, scaleScratch2) as Cartesian2
    const scaleRatioX = scale / existingScale.x
    const scaleRatioY = scale / existingScale.y

    result[0] = matrix[0] * scaleRatioX
    result[1] = matrix[1] * scaleRatioX
    result[2] = matrix[2] * scaleRatioY
    result[3] = matrix[3] * scaleRatioY

    return result
  }

  /**
   * Extracts the non-uniform scale assuming the matrix is an affine transformation.
   *
   * @param {Matrix2} matrix The matrix.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   *
   * @see Matrix2.multiplyByScale
   * @see Matrix2.multiplyByUniformScale
   * @see Matrix2.fromScale
   * @see Matrix2.fromUniformScale
   * @see Matrix2.setScale
   * @see Matrix2.setUniformScale
   */
  public static getScale(
    matrix: Matrix2, 
    result?: ICartesian): ICartesian | undefined {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    if (!defined(result)) {
      result = new Cartesian2();
    }
    result!.x = Cartesian2.magnitude(Cartesian2.fromElements(matrix[0], matrix[1], scratchColumn) as Cartesian2)
    result!.y = Cartesian2.magnitude(Cartesian2.fromElements(matrix[2], matrix[3], scratchColumn)as Cartesian2)
    return result
  }

  /**
   * Computes the maximum scale assuming the matrix is an affine transformation.
   * The maximum scale is the maximum length of the column vectors.
   *
   * @param {Matrix2} matrix The matrix.
   * @returns {number} The maximum scale.
   */
  public static getMaximumScale(matrix: Matrix2): number {
    Matrix2.getScale(matrix, scaleScratch3)
    return Cartesian2.maximumComponent(scaleScratch3)
  }

  /**
   * Sets the rotation assuming the matrix is an affine transformation.
   *
   * @param {Matrix2} matrix The matrix.
   * @param {Matrix2} rotation The rotation matrix.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   * @see Matrix2.fromRotation
   * @see Matrix2.getRotation
   */
  public static setRotation(matrix: Matrix2, rotation: Matrix2, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    const scale = Matrix2.getScale(matrix, scaleScratch4) as Cartesian2

    result[0] = rotation[0] * scale.x
    result[1] = rotation[1] * scale.x
    result[2] = rotation[2] * scale.y
    result[3] = rotation[3] * scale.y

    return result
  }

  /**
   * Extracts the rotation matrix assuming the matrix is an affine transformation.
   *
   * @param {Matrix2} matrix The matrix.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   * @see Matrix2.setRotation
   * @see Matrix2.fromRotation
   */
  public static getRotation(matrix: Matrix2, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    const scale = Matrix2.getScale(matrix, scaleScratch5) as Cartesian2

    result[0] = matrix[0] / scale.x
    result[1] = matrix[1] / scale.x
    result[2] = matrix[2] / scale.y
    result[3] = matrix[3] / scale.y

    return result
  }

  /**
   * Computes the product of two matrices.
   *
   * @param {Matrix2} left The first matrix.
   * @param {Matrix2} right The second matrix.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  public static multiply(left: Matrix2, right: Matrix2, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('left', left)
    Check.typeOf.object('right', right)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    const column0Row0 = left[0] * right[0] + left[2] * right[1]
    const column1Row0 = left[0] * right[2] + left[2] * right[3]
    const column0Row1 = left[1] * right[0] + left[3] * right[1]
    const column1Row1 = left[1] * right[2] + left[3] * right[3]

    result[0] = column0Row0
    result[1] = column0Row1
    result[2] = column1Row0
    result[3] = column1Row1
    return result
  }

  /**
   * Computes the sum of two matrices.
   *
   * @param {Matrix2} left The first matrix.
   * @param {Matrix2} right The second matrix.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  public static add(left: Matrix2, right: Matrix2, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('left', left)
    Check.typeOf.object('right', right)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    result[0] = left[0] + right[0]
    result[1] = left[1] + right[1]
    result[2] = left[2] + right[2]
    result[3] = left[3] + right[3]
    return result
  }

  /**
   * Computes the difference of two matrices.
   *
   * @param {Matrix2} left The first matrix.
   * @param {Matrix2} right The second matrix.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  public static subtract(left: Matrix2, right: Matrix2, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('left', left)
    Check.typeOf.object('right', right)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    result[0] = left[0] - right[0]
    result[1] = left[1] - right[1]
    result[2] = left[2] - right[2]
    result[3] = left[3] - right[3]
    return result
  }

  /**
   * Computes the product of a matrix and a column vector.
   *
   * @param {Matrix2} matrix The matrix.
   * @param {Cartesian2} cartesian The column.
   * @param {Cartesian2} result The object onto which to store the result.
   * @returns {Cartesian2} The modified result parameter.
   */
  public static multiplyByVector(
    matrix: Matrix2,
    cartesian: ICartesian,
    result: ICartesian,
  ): ICartesian | undefined {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    Check.typeOf.object('cartesian', cartesian)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    const x = matrix[0] * cartesian.x + matrix[2] * cartesian.y
    const y = matrix[1] * cartesian.x + matrix[3] * cartesian.y

    result.x = x
    result.y = y
    return result
  }

  /**
   * Computes the product of a matrix and a scalar.
   *
   * @param {Matrix2} matrix The matrix.
   * @param {number} scalar The number to multiply by.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  public static multiplyByScalar(matrix: Matrix2, scalar: number, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    Check.typeOf.number('scalar', scalar)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    result[0] = matrix[0] * scalar
    result[1] = matrix[1] * scalar
    result[2] = matrix[2] * scalar
    result[3] = matrix[3] * scalar
    return result
  }

  /**
   * Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
   *
   * @param {Matrix2} matrix The matrix on the left-hand side.
   * @param {Cartesian2} scale The non-uniform scale on the right-hand side.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   *
   * @example
   * // Instead of Matrix2.multiply(m, Matrix2.fromScale(scale), m);
   * Matrix2.multiplyByScale(m, scale, m);
   *
   * @see Matrix2.multiplyByUniformScale
   * @see Matrix2.fromScale
   * @see Matrix2.fromUniformScale
   * @see Matrix2.setScale
   * @see Matrix2.setUniformScale
   * @see Matrix2.getScale
   */
  public static multiplyByScale(matrix: Matrix2, scale: ICartesian, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    Check.typeOf.object('scale', scale)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    result[0] = matrix[0] * scale.x
    result[1] = matrix[1] * scale.x
    result[2] = matrix[2] * scale.y
    result[3] = matrix[3] * scale.y

    return result
  }

  /**
   * Computes the product of a matrix times a uniform scale, as if the scale were a scale matrix.
   *
   * @param {Matrix2} matrix The matrix on the left-hand side.
   * @param {number} scale The uniform scale on the right-hand side.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   *
   * @example
   * // Instead of Matrix2.multiply(m, Matrix2.fromUniformScale(scale), m);
   * Matrix2.multiplyByUniformScale(m, scale, m);
   *
   * @see Matrix2.multiplyByScale
   * @see Matrix2.fromScale
   * @see Matrix2.fromUniformScale
   * @see Matrix2.setScale
   * @see Matrix2.setUniformScale
   * @see Matrix2.getScale
   */
  public static multiplyByUniformScale(matrix: Matrix2, scale: number, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    Check.typeOf.number('scale', scale)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    result[0] = matrix[0] * scale
    result[1] = matrix[1] * scale
    result[2] = matrix[2] * scale
    result[3] = matrix[3] * scale

    return result
  }

  /**
   * Creates a negated copy of the provided matrix.
   *
   * @param {Matrix2} matrix The matrix to negate.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  public static negate(matrix: Matrix2, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    result[0] = -matrix[0]
    result[1] = -matrix[1]
    result[2] = -matrix[2]
    result[3] = -matrix[3]
    return result
  }

  /**
   * Computes the transpose of the provided matrix.
   *
   * @param {Matrix2} matrix The matrix to transpose.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  public static transpose(matrix: Matrix2, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    const column0Row0 = matrix[0]
    const column0Row1 = matrix[2]
    const column1Row0 = matrix[1]
    const column1Row1 = matrix[3]

    result[0] = column0Row0
    result[1] = column0Row1
    result[2] = column1Row0
    result[3] = column1Row1
    return result
  }

  /**
   * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
   *
   * @param {Matrix2} matrix The matrix with signed elements.
   * @param {Matrix2} result The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter.
   */
  public static abs(matrix: Matrix2, result: Matrix2): Matrix2 {
    //>>includeStart('debug', pragmas.debug);
    Check.typeOf.object('matrix', matrix)
    Check.typeOf.object('result', result)
    //>>includeEnd('debug');

    result[0] = Math.abs(matrix[0])
    result[1] = Math.abs(matrix[1])
    result[2] = Math.abs(matrix[2])
    result[3] = Math.abs(matrix[3])

    return result
  }

  /**
   * Compares the provided matrices componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Matrix2} [left] The first matrix.
   * @param {Matrix2} [right] The second matrix.
   * @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  public static equals(left: Matrix2, right: Matrix2): boolean {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left[0] === right[0] &&
        left[1] === right[1] &&
        left[2] === right[2] &&
        left[3] === right[3])
    )
  }

  /**
   * @private
   */
  public static equalsArray(matrix: Matrix2, array: Array<number>, offset: number): boolean {
    return (
      matrix[0] === array[offset] &&
      matrix[1] === array[offset + 1] &&
      matrix[2] === array[offset + 2] &&
      matrix[3] === array[offset + 3]
    )
  }

  /**
   * Compares the provided matrices componentwise and returns
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> otherwise.
   *
   * @param {Matrix2} [left] The first matrix.
   * @param {Matrix2} [right] The second matrix.
   * @param {number} [epsilon=0] The epsilon to use for equality testing.
   * @returns {boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
   */
  public static equalsEpsilon(left: Matrix2, right: Matrix2, epsilon: number): boolean {
    epsilon = epsilon ?? 0
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        Math.abs(left[0] - right[0]) <= epsilon &&
        Math.abs(left[1] - right[1]) <= epsilon &&
        Math.abs(left[2] - right[2]) <= epsilon &&
        Math.abs(left[3] - right[3]) <= epsilon)
    )
  }

  /**
   * An immutable Matrix2 instance initialized to the identity matrix.
   *
   * @type {Matrix2}
   * @constant
   */
  public static readonly IDENTITY = Object.freeze(new Matrix2(1.0, 0.0, 0.0, 1.0))

  /**
   * An immutable Matrix2 instance initialized to the zero matrix.
   *
   * @type {Matrix2}
   * @constant
   */
  public static readonly ZERO = Object.freeze(new Matrix2(0.0, 0.0, 0.0, 0.0))

  /**
   * The index into Matrix2 for column 0, row 0.
   *
   * @type {number}
   * @constant
   *
   * @example
   * const matrix = new Matrix2();
   * matrix[Matrix2.COLUMN0ROW0] = 5.0; // set column 0, row 0 to 5.0
   */
  public static readonly COLUMN0ROW0 = 0

  /**
   * The index into Matrix2 for column 0, row 1.
   *
   * @type {number}
   * @constant
   *
   * @example
   * const matrix = new Matrix2();
   * matrix[Matrix2.COLUMN0ROW1] = 5.0; // set column 0, row 1 to 5.0
   */
  public static readonly COLUMN0ROW1 = 1

  /**
   * The index into Matrix2 for column 1, row 0.
   *
   * @type {number}
   * @constant
   *
   * @example
   * const matrix = new Matrix2();
   * matrix[Matrix2.COLUMN1ROW0] = 5.0; // set column 1, row 0 to 5.0
   */
  public static readonly COLUMN1ROW0 = 2

  /**
   * The index into Matrix2 for column 1, row 1.
   *
   * @type {number}
   * @constant
   *
   * @example
   * const matrix = new Matrix2();
   * matrix[Matrix2.COLUMN1ROW1] = 5.0; // set column 1, row 1 to 5.0
   */
  public static readonly COLUMN1ROW1 = 3
  /**
   * Gets the number of items in the collection.
   * @memberof Matrix2.prototype
   *
   * @type {number}
   */
  public get length() {
    return Matrix2.packedLength
  }
  /**
   * Duplicates the provided Matrix2 instance.
   *
   * @param {Matrix2} [result] The object onto which to store the result.
   * @returns {Matrix2} The modified result parameter or a new Matrix2 instance if one was not provided.
   */
  public clone(result: Matrix2): Matrix2 | undefined {
    return Matrix2.clone(this, result)
  }

  /**
   * Compares this matrix to the provided matrix componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Matrix2} [right] The right hand side matrix.
   * @returns {boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  public equals(right: Matrix2): boolean {
    return Matrix2.equals(this, right)
  }

  /**
   * Compares this matrix to the provided matrix componentwise and returns
   * <code>true</code> if they are within the provided epsilon,
   * <code>false</code> otherwise.
   *
   * @param {Matrix2} [right] The right hand side matrix.
   * @param {number} [epsilon=0] The epsilon to use for equality testing.
   * @returns {boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
   */
  public equalsEpsilon(right: Matrix2, epsilon: number): boolean {
    return Matrix2.equalsEpsilon(this, right, epsilon)
  }

  /**
   * Creates a string representing this Matrix with each row being
   * on a separate line and in the format '(column0, column1)'.
   *
   * @returns {string} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1)'.
   */
  public toString(): string {
    return `(${this[0]}, ${this[2]})\n` + `(${this[1]}, ${this[3]})`
  }
} // end class Matrix2
const scaleScratch1 = new Cartesian2()
const scaleScratch2 = new Cartesian2()
const scratchColumn = new Cartesian2()

const scaleScratch3 = new Cartesian2()
const scaleScratch4 = new Cartesian2()
const scaleScratch5 = new Cartesian2()
